package org.jeecg.modules.zhouAdmin.admin.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.degression.mapper.FactoryCategoryMapper;
import org.jeecg.modules.degression.mapper.FactoryRecordMapper;
import org.jeecg.modules.degression.mapper.MyMlccPricesystemFactoryRangeMapper;
import org.jeecg.modules.degression.pojo.MlccPriceSystemFactoryRecord;
import org.jeecg.modules.degression.pojo.MlccPricesystemFactoryCategory;
import org.jeecg.modules.degression.pojo.MlccPricesystemFactoryRange;
import org.jeecg.modules.gwcjava.jiekou.entity.MlccUserInfo;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.mapper.*;
import org.jeecg.modules.zhouAdmin.admin.goodsCenter.pojo.*;
import org.jeecg.modules.zhoupackage.mapper.*;
import org.jeecg.modules.zhoupackage.pojo.*;
import org.jeecg.modules.zhoupackage.service.ITeamOrderService;
import org.jeecg.modules.zhoupackage.util.FabricUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

/**
 * 个订和团订的工具类
 */
@Component
public class SingleAndTeamOrderUtil {

    @Autowired
    private MyMlccProductInfoMapper productInfoMapper;

    @Autowired
    private FactoryCategoryMapper factoryCategoryMapper;

    @Autowired
    private FactoryRecordMapper factoryRecordMapper;

    @Autowired
    MyMlccPricesystemFactoryRangeMapper factoryRangeMapper;

    @Autowired
    MyMlccThirdOutstorageDanMapper danMapper;

    @Autowired
    MlccFabricInfoMapper fabricInfoMapper;

    @Autowired
    MyMlccFabricOrderinfoMapper fabricOrderinfoMapper;

    @Autowired
    MlccCartInfoMapper cartInfoMapper;

    @Autowired
    MyMlccThirdOutstorageGoodsMapper outstorageGoodsMapper;

    @Autowired
    MyMlccSingleOrderInfoMapper singleOrderInfoMapper;

    @Autowired
    FabricUtil fabricUtil;

    @Autowired
    CartMlccUserInfoMapper userInfoMapper;

    @Autowired
    ITeamOrderService teamOrderService;

    @Autowired
    MyMlccThirdGoodsMapper goodsMapper;

    @Autowired
    MysmallProductMapper smallProMapper;

    @Autowired
    MyMlccThirdGoodsSeriesMapper goodsSeriesMapper;

    @Autowired
    MyMlccThirdGoodsRangeMapper rangeMapper;

    @Autowired
    MyMlccThirdOutventoryitemsMapper outventoryitemsMapper;

    @Autowired
    MyMlccThirdInventoryitemsMapper inventoryitemsMapper;

    @Autowired
    MyMlccThirdRemainingInventoryMapper remainingInventoryMapper;

    /**
     * 获取个订订单下的所有产品
     *
     * @param orderSn 个订订单编号
     */
    public List<MlccProductInfo> listProFromSingleOrder(String orderSn) {
        QueryWrapper<MlccProductInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        return productInfoMapper.selectList(wrapper);
    }

    /**
     * 确定工厂的价格体系
     *
     * @param gysid        供应商id
     * @param plid         品类id
     * @param businessType 默认0个订业务，1团订业务，2标准码业务
     * @param isGongyi     是否是品类：默认0品类，1工艺
     */
    public MlccPricesystemFactoryCategory factoryCategory(String gysid, String plid, Integer businessType, Integer isGongyi) {
        QueryWrapper<MlccPricesystemFactoryCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("sys_user_id", gysid).eq("category_id", plid).eq("business_type", businessType).eq("is_gongyi", isGongyi);
        return factoryCategoryMapper.selectOne(wrapper);
    }

    /**
     * 获取指定品类下指定供应商的所偶已近设置的成本项
     *
     * @param plid                   品类ID
     * @param pricesystem_factory_id 价格体系id
     */
    public List<MlccPriceSystemFactoryRecord> listFactoryRecord(String plid, String pricesystem_factory_id) {
        QueryWrapper<MlccPriceSystemFactoryRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("cost_item", plid).eq("status", 1).eq("pricesystem_factory_id", pricesystem_factory_id);
        return factoryRecordMapper.selectList(wrapper);
    }

    /**
     * 获取指定品类下指定供应商的设置的返修成本
     *
     * @param plid                   品类ID
     * @param pricesystem_factory_id 价格体系id
     * @param sizeid                 尺寸ID
     */
    public List<MlccPriceSystemFactoryRecord> listFactoryFanxiuRecord(String plid, String pricesystem_factory_id, String sizeid) {
        QueryWrapper<MlccPriceSystemFactoryRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("cost_item", plid).eq("status", 1).eq("pricesystem_factory_id", pricesystem_factory_id)
                .eq("type", 6).eq("cost_id", sizeid);
        return factoryRecordMapper.selectList(wrapper);
    }

    /**
     * 获取产品的工艺区间价格记录
     *
     * @param pricesystem_factory_id 价格体系id
     * @param productCount           产品数量
     */
    public MlccPricesystemFactoryRange getrange(String pricesystem_factory_id, Integer productCount) {
        QueryWrapper<MlccPricesystemFactoryRange> wrapper = new QueryWrapper<>();
        System.out.println("价格体系id" + pricesystem_factory_id);
        wrapper.eq("pricesystem_factory_id", pricesystem_factory_id)
                .le("min_numbers", productCount).gt("max_numbers", productCount).eq("status", 0);
        return factoryRangeMapper.selectOne(wrapper);
    }

    /**
     * 向出库申请表添加记录
     *
     * @param orderSn   订单编号
     * @param orderType 订单类型：默认0面料订单，1个订订单，2团订订单，3成衣订单
     */
    public void addChuku(String orderSn, Integer orderType) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 出库申请表添加记录
        MlccThirdOutstorageDan outstorageDan = new MlccThirdOutstorageDan();
        outstorageDan.setId(UUID.randomUUID().toString()).setCode(UUID.randomUUID().toString())
                .setOrderSn(orderSn).setOrderType(orderType).setCreateBy(user.getRealname())
                .setUpdateBy(user.getRealname());
        int insert = danMapper.insert(outstorageDan);
        if (insert > 0) {
            // 出库商品表添加记录
            if (orderType == 0) {
                // 如果是面料订单，插入每一种面料的钱
                saveFabricOutGoods(orderSn, outstorageDan.getId(), user);
            } else if (orderType == 1) {
                // 个订需要插入面料的钱
                saveSingleOutGoods(orderSn, outstorageDan.getId(), user);
            } else if (orderType == 2) {
                // 团订需要插入面料和现货的钱
                saveTeamOutGoods(orderSn, outstorageDan.getId(), user);
            }
        }
    }

    /**
     * 面料订单向出库商品表添加记录
     *
     * @param orderSn 面料订单编号
     * @param outid   出库申请表id
     * @param user    当前登录账号
     */
    public void saveFabricOutGoods(String orderSn, String outid, LoginUser user) {
        QueryWrapper<MlccFabricOrderinfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccFabricOrderinfo info = fabricOrderinfoMapper.selectOne(wrapper);
        if (info != null) {
            // 获取购物车
            String[] carts = info.getCartId().split(",");
            for (String cartid : carts) {
                MlccCartInfo mlccCartInfo = cartInfoMapper.selectById(cartid);
                if (mlccCartInfo != null) {
                    MlccThirdOutstorageGoods outstorageGoods = new MlccThirdOutstorageGoods();
                    outstorageGoods.setId(UUID.randomUUID().toString()).setCode(UUID.randomUUID().toString())
                            .setGoodsId(mlccCartInfo.getFabricId()).setOrderBuynum(mlccCartInfo.getBuyNumber())
                            .setOrderGoodsPrice(Double.valueOf(mlccCartInfo.getTotalAmount())).setOutstorageDanId(outid)
                            .setGoodsType(1).setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
                    outstorageGoodsMapper.insert(outstorageGoods);
                    // 出库项表添加记录
                    saveChuku(outstorageGoods);
                }
            }
        }
    }

    /**
     * 个订订单向出库商品表添加记录
     *
     * @param orderSn 个订订单编号
     * @param outid   出库申请表id
     * @param user    当前登录账号
     */
    public void saveSingleOutGoods(String orderSn, String outid, LoginUser user) {
        QueryWrapper<MlccSingleOrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("order_sn", orderSn);
        MlccSingleOrderInfo singleOrderInfo = singleOrderInfoMapper.selectOne(wrapper);
        ArrayList<MlccFabricInfo> allFabric = new ArrayList<>(); // 用来存放这个订单中的所有面料

        // 用户基本信息
        MlccUserInfo userDetail = userInfoMapper.selectById(singleOrderInfo.getUserId());

        // 1、获取订单中的产品数据
        List<String> chanpingids = Arrays.asList(singleOrderInfo.getChanpingIds().split(","));
        QueryWrapper<MlccProductInfo> wrapper1 = new QueryWrapper<>();
        wrapper1.in("id", chanpingids).orderByDesc("create_time");
        List<MlccProductInfo> productInfoList = productInfoMapper.selectList(wrapper1);// 这是所有的产品

        for (MlccProductInfo newProductInfo : productInfoList) {
            // 3、从产品数据中查询面料数据
            if (newProductInfo.getFabricIds() != null && !"".equals(newProductInfo.getFabricIds())) {
                double zhekou = 1;
                // 存放这个产品的下的所有面料
                HashSet<MlccFabricInfo> fabricInfoSet = new HashSet<>();
                // 查询产品的面料ids 面料id/购买米数
                List<String> fabricids = Arrays.asList(newProductInfo.getFabricIds().split(","));
                if (fabricids != null && fabricids.size() > 0) {
                    // 循环遍历
                    for (String fabricid : fabricids) {
                        String[] split = fabricid.split("/");
                        // 查询到面料的基本信息
                        MlccFabricInfo mlccFabricInfos = fabricInfoMapper.selectById(split[0]);
                        // 重新查询面料的价格(拿到了标准单价)
                        mlccFabricInfos = fabricUtil.addPrice(mlccFabricInfos, Double.valueOf(split[1]));
                        if (mlccFabricInfos.getGroupId() != null) {
                            // 获取面料折扣
                            zhekou = fabricUtil.userFabricDiscount(userDetail.getId() + "", mlccFabricInfos.getGroupId());
                        }
                        mlccFabricInfos.setKehuzk(zhekou);
                        mlccFabricInfos.setMishu(split[1]);
                        fabricInfoSet.add(mlccFabricInfos);
                        allFabric.add(mlccFabricInfos);
                    }
                }
            }
        }

        // 计算面料价格
        for (MlccFabricInfo fabricInfo : allFabric) {
            if (fabricInfo != null) {
                if (fabricInfo.getFabricPrice() == null) {
                    fabricInfo.setFabricPrice(new BigDecimal(0));
                }
                // 计算折后单价
                BigDecimal multiply = fabricInfo.getFabricPrice().multiply(new BigDecimal(fabricInfo.getKehuzk()));
                fabricInfo.setAfterPrice(multiply.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                // 计算单种面料的总价
                BigDecimal multiply1 = new BigDecimal(fabricInfo.getAfterPrice()).multiply(new BigDecimal(Double.valueOf(fabricInfo.getMishu())));
                fabricInfo.setAllPrice(multiply1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                // orderMoney = orderMoney.add(new BigDecimal(fabricInfo.getAllPrice()));

                // 往出库商品表添加记录
                MlccThirdOutstorageGoods goods = new MlccThirdOutstorageGoods();
                goods.setId(UUID.randomUUID().toString()).setCode(UUID.randomUUID().toString())
                        .setGoodsId(fabricInfo.getId() + "").setOrderBuynum(Double.valueOf(fabricInfo.getMishu()))
                        .setOrderGoodsPrice(fabricInfo.getAllPrice()).setOutstorageDanId(outid).setGoodsType(1)
                        .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
                outstorageGoodsMapper.insert(goods);
                // 出库项表添加记录
                saveChuku(goods);
            }
        }
    }

    /**
     * 团订订单向出库商品表添加记录
     *
     * @param orderSn 团订订单编号
     * @param outid   出库申请表id
     * @param user    当前登录账号
     */
    public void saveTeamOutGoods(String orderSn, String outid, LoginUser user) {
        // 团订订单详情
        MlccTeamOrderInfo teamOrderInfo = teamOrderService.previewOrder(orderSn);
        List<MlccFabricInfo> allFabric = teamOrderInfo.getAllFabric();
        if (allFabric != null && allFabric.size() > 0) {
            for (MlccFabricInfo fabricInfo : allFabric) {
                // 往出库商品表添加记录，首先是添加面料
                MlccThirdOutstorageGoods goods = new MlccThirdOutstorageGoods();
                goods.setId(UUID.randomUUID().toString()).setCode(UUID.randomUUID().toString())
                        .setGoodsId(fabricInfo.getId() + "").setOrderBuynum(Double.valueOf(fabricInfo.getMishu()))
                        .setOrderGoodsPrice(fabricInfo.getAllPrice()).setOutstorageDanId(outid).setGoodsType(1)
                        .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
                outstorageGoodsMapper.insert(goods);
                // 出库项表添加记录
                saveChuku(goods);
            }
        }

        // 其次是添加商品的出库
        List<MlccProductInfo> allPro = teamOrderInfo.getAllPro();
        if (allPro != null && allPro.size() > 0) {
            for (MlccProductInfo info : allPro) {
                if (info.getGoodsid() != null && !"".equals(info.getGoodsid())) {
                    MlccThirdGoods thirdGoods = goodsMapper.selectById(info.getGoodsid());
                    // 查询现货的小产品数量
                    QueryWrapper<MlccCustomerProductInfo> wrapper = new QueryWrapper<>();
                    wrapper.eq("product_id", info.getId());
                    int count = smallProMapper.selectCount(wrapper);

                    // 获取商品的价格
                    BigDecimal price = goodsPrice(thirdGoods.getId(), count);
                    // 计算产品下商品的总价
                    BigDecimal ProPrice = price.multiply(new BigDecimal(count));

                    // 往出库商品表添加记录，现在是添加现货商品
                    MlccThirdOutstorageGoods goods = new MlccThirdOutstorageGoods();
                    goods.setId(UUID.randomUUID().toString()).setCode(UUID.randomUUID().toString())
                            .setGoodsId(thirdGoods.getId()).setOrderBuynum(new Double(count))
                            .setOrderGoodsPrice(ProPrice.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())
                            .setOutstorageDanId(outid).setGoodsType(0)
                            .setCreateBy(user.getRealname()).setUpdateBy(user.getRealname());
                    outstorageGoodsMapper.insert(goods);
                    // 出库项表添加记录
                    saveChuku(goods);
                }
            }
        }
    }

    /**
     * 根据商品id获取商品的价格
     *
     * @param goodsid 商品id
     * @param number  购买数量
     */
    public BigDecimal goodsPrice(String goodsid, Integer number) {
        BigDecimal price = new BigDecimal(0);
        MlccThirdGoods goods = goodsMapper.selectById(goodsid);
        if (goods != null) {
            // 是否是主推商品？
            if (goods.getIsMain() == 1) {
                return goods.getPrice();
            }
            // 获取商品系列
            MlccThirdGoodsSeries group = goodsSeriesMapper.selectById(goods.getGoodsSeriesId());
            if (group != null) {
                // 默认价格就是系列的单价
                price = group.getRetailPrice();
                QueryWrapper<MlccThirdGoodsRange> wrapper = new QueryWrapper<>();
                wrapper.eq("goods_series_id", group.getId());
                List<MlccThirdGoodsRange> ranges = rangeMapper.selectList(wrapper);
                if (ranges != null && ranges.size() > 0) {
                    for (MlccThirdGoodsRange range : ranges) {
                        // 是否由符合的区间
                        if (number >= range.getMin() && number < range.getMax()) {
                            price = range.getPrice();
                        }
                    }
                }
            }
        }
        return price;
    }

    /**
     * 出库项表添加记录
     *
     * @param outGoods 出库商品数据
     */
    public void saveChuku(MlccThirdOutstorageGoods outGoods) {
        // 根据商品id查询批次表
        QueryWrapper<MlccThirdRemainingInventory> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", outGoods.getGoodsId()).eq("status", 1);
        List<MlccThirdRemainingInventory> list = remainingInventoryMapper.selectList(wrapper);
        if (list != null && list.size() > 0) {
            // 把所有查到的批次项目插入到出库项表
            for (MlccThirdRemainingInventory inventoryitems : list) {
                MlccThirdOutventoryitems out = new MlccThirdOutventoryitems();
                out.setId(UUID.randomUUID().toString()).setCode(inventoryitems.getBatchCode())
                        .setBatchName(inventoryitems.getBatchName()).setGoodsId(inventoryitems.getGoodsId())
                        .setInventoryitemsId(inventoryitems.getInventoryitemsId()).setOutstorageDanId(outGoods.getOutstorageDanId())
                        .setOutstorageGoodsId(outGoods.getId()).setOutcount(Double.valueOf(inventoryitems.getNewCount()))
                        .setGoodsType(outGoods.getGoodsType());
                outventoryitemsMapper.insert(out);
            }
        }
    }
}
